package com.liu;

import java.awt.*;
import java.awt.event.KeyEvent;

public class Snake {
        Node head,tail; //head结点和尾结点默认为空
        Dir dir =Dir.L;
        Snake(){
            head = new Node(20,20);//把蛇的脑袋放在20行20列那边

            tail =head;
        }

    public void paint(Graphics g) {
            Node n =head;
            while(n!=null){
                n.paint(g); //把节点画出来，因为这里存储蛇的数据结构是 一个Node,所以这里的意思就是把蛇的每节一结画出来
                n=n.next;
            }
            move(); //蛇的移动，和电影动画的原理一样，

        }



        public void addToHead(){//增加蛇头
            Node n =null;
            switch (dir){
                case L:
                    n = new Node(head.row ,head.col-1); //朝上增加蛇的节点
                    break;
                case U:
                    n = new Node(head.row-1 ,head.col); //朝下增加蛇的节点
                    break;
                case R:
                    n = new Node(head.row ,head.col+1);
                    break;
                case D:
                    n = new Node(head.row +1,head.col);
                    break;

            }
            //这一部分最重要。把new出来的这个Node n给他加载蛇的头部
            n.next =head;
            head.prev=n;
            head =n;

        }

        private void deleteTail(){
            if(tail ==null) {
                return ;
            }

                tail =tail.prev;
                tail.next.prev =null;
                tail.next=null;

        }
        private void move(){
            addToHead(); //增加蛇头
            deleteTail();//删除蛇尾
            boundaryCheck();//边界检测

        }

    private void boundaryCheck() {
            if(head.row<0) head.row =Yard.NodeCount-1;
            if(head.col<0) head.col = Yard.NodeCount-1;
            if(head.row>Yard.NodeCount-1) head.row =0;
            if(head.col>Yard.NodeCount-1) head.col =0;


    }

    public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            switch(key){
                case KeyEvent.VK_LEFT:
                    dir =Dir.L;
                    break;
                case KeyEvent.VK_UP:
                    dir =Dir.U;
                    break;
                case KeyEvent.VK_RIGHT:
                    dir= Dir.R;
                    break;
                case KeyEvent.VK_DOWN:
                    dir =Dir.D;
                    break;


            }
        }
        public void eat(Egg e){
            if(head.row ==e.row && head.col == e.col){
                addToHead();
                e.reApperar();
            }
        }


}











